package com.YHVision.qiuzhike.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.YHVision.qiuzhike.annotation.AuthCheck;
import com.YHVision.qiuzhike.common.BaseResponse;
import com.YHVision.qiuzhike.common.DeleteRequest;
import com.YHVision.qiuzhike.common.ErrorCode;
import com.YHVision.qiuzhike.common.ResultUtils;
import com.YHVision.qiuzhike.constant.UserConstant;
import com.YHVision.qiuzhike.exception.BusinessException;
import com.YHVision.qiuzhike.exception.ThrowUtils;
import com.YHVision.qiuzhike.model.dto.postBankCompany.PostBankCompanyAddRequest;
import com.YHVision.qiuzhike.model.dto.postBankCompany.PostBankCompanyQueryRequest;
import com.YHVision.qiuzhike.model.dto.postBankCompany.PostBankCompanyUpdateRequest;
import com.YHVision.qiuzhike.model.entity.PostBankCompany;
import com.YHVision.qiuzhike.model.entity.User;
import com.YHVision.qiuzhike.model.vo.PostBankCompanyVO;
import com.YHVision.qiuzhike.service.PostBankCompanyService;
import com.YHVision.qiuzhike.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 职位企业关联接口
 *
 * @author <a href="">YHVision-小y</a>
 * @from <a href="todo">爱编程学习圈</a>
 */
@RestController
@RequestMapping("/postBankCompany")
@Slf4j
public class PostBankCompanyController {

    @Resource
    private PostBankCompanyService postBankCompanyService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建职位企业关联
     *
     * @param postBankCompanyAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addPostBankCompany(@RequestBody PostBankCompanyAddRequest postBankCompanyAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(postBankCompanyAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        PostBankCompany postBankCompany = new PostBankCompany();
        BeanUtils.copyProperties(postBankCompanyAddRequest, postBankCompany);
        // 数据校验
        postBankCompanyService.validPostBankCompany(postBankCompany, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        postBankCompany.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = postBankCompanyService.save(postBankCompany);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newPostBankCompanyId = postBankCompany.getId();
        return ResultUtils.success(newPostBankCompanyId);
    }

    /**
     * 删除职位企业关联
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePostBankCompany(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        PostBankCompany oldPostBankCompany = postBankCompanyService.getById(id);
        ThrowUtils.throwIf(oldPostBankCompany == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPostBankCompany.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = postBankCompanyService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新职位企业关联（仅管理员可用）
     *
     * @param postBankCompanyUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePostBankCompany(@RequestBody PostBankCompanyUpdateRequest postBankCompanyUpdateRequest) {
        if (postBankCompanyUpdateRequest == null || postBankCompanyUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        PostBankCompany postBankCompany = new PostBankCompany();
        BeanUtils.copyProperties(postBankCompanyUpdateRequest, postBankCompany);
        // 数据校验
        postBankCompanyService.validPostBankCompany(postBankCompany, false);
        // 判断是否存在
        long id = postBankCompanyUpdateRequest.getId();
        PostBankCompany oldPostBankCompany = postBankCompanyService.getById(id);
        ThrowUtils.throwIf(oldPostBankCompany == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = postBankCompanyService.updateById(postBankCompany);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取职位企业关联（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PostBankCompanyVO> getPostBankCompanyVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        PostBankCompany postBankCompany = postBankCompanyService.getById(id);
        ThrowUtils.throwIf(postBankCompany == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(postBankCompanyService.getPostBankCompanyVO(postBankCompany, request));
    }

    /**
     * 分页获取职位企业关联列表（仅管理员可用）
     *
     * @param postBankCompanyQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<PostBankCompany>> listPostBankCompanyByPage(@RequestBody PostBankCompanyQueryRequest postBankCompanyQueryRequest) {
        long current = postBankCompanyQueryRequest.getCurrent();
        long size = postBankCompanyQueryRequest.getPageSize();
        // 查询数据库
        Page<PostBankCompany> postBankCompanyPage = postBankCompanyService.page(new Page<>(current, size),
                postBankCompanyService.getQueryWrapper(postBankCompanyQueryRequest));
        return ResultUtils.success(postBankCompanyPage);
    }

    /**
     * 分页获取职位企业关联列表（封装类）
     *
     * @param postBankCompanyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PostBankCompanyVO>> listPostBankCompanyVOByPage(@RequestBody PostBankCompanyQueryRequest postBankCompanyQueryRequest,
                                                               HttpServletRequest request) {
        long current = postBankCompanyQueryRequest.getCurrent();
        long size = postBankCompanyQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<PostBankCompany> postBankCompanyPage = postBankCompanyService.page(new Page<>(current, size),
                postBankCompanyService.getQueryWrapper(postBankCompanyQueryRequest));
        // 获取封装类
        return ResultUtils.success(postBankCompanyService.getPostBankCompanyVOPage(postBankCompanyPage, request));
    }

    /**
     * 分页获取当前登录用户创建的职位企业关联列表
     *
     * @param postBankCompanyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<PostBankCompanyVO>> listMyPostBankCompanyVOByPage(@RequestBody PostBankCompanyQueryRequest postBankCompanyQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(postBankCompanyQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        postBankCompanyQueryRequest.setUserId(loginUser.getId());
        long current = postBankCompanyQueryRequest.getCurrent();
        long size = postBankCompanyQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<PostBankCompany> postBankCompanyPage = postBankCompanyService.page(new Page<>(current, size),
                postBankCompanyService.getQueryWrapper(postBankCompanyQueryRequest));
        // 获取封装类
        return ResultUtils.success(postBankCompanyService.getPostBankCompanyVOPage(postBankCompanyPage, request));
    }

    // endregion
}
